package com.xiaopangzi.websocket.directive.config;

import com.xiaopangzi.websocket.directive.handler.MyTextWebSocketHandler;
import com.xiaopangzi.websocket.directive.intercepter.MyHandshakeInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;

import javax.websocket.ContainerProvider;
import javax.websocket.WebSocketContainer;

/**
 * 描述: WebSocket服务的配置类
 *
 * @author : sujinchen
 * @date : 2020/9/22
 */
@Configuration
/**
 * 允许WebSocket使用
 */
@EnableWebSocket
public class MyWebSocketConfig implements WebSocketConfigurer {
    /**
     * 配置MyTextWebSocketHandler
     * @return
     */
    @Bean
    public MyTextWebSocketHandler myTextWebSocketHandler() {
        return new MyTextWebSocketHandler();
    }


    /**
     * 注册WebSocketHandlers的配置
     * @param registry
     */
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        //将自定义的服务站点映射到/myTextWs地址
        registry.addHandler(myTextWebSocketHandler(), "/myTextWs")
                //添加握手拦截器
                .addInterceptors(new MyHandshakeInterceptor())
                //配置允许的来源
                .setAllowedOrigins("http://www.baidu.com", "http://localhost:8080", "http://localhost:63342")
        .withSockJS();
    }

    /**
     * 将ServletServerContainerFactoryBean添加到 WebSocket Java 配置中
     * @return
     */
    @Bean
    public ServletServerContainerFactoryBean createWebSocketContainer() {

        ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
        container.setMaxTextMessageBufferSize(8192);
        container.setMaxBinaryMessageBufferSize(8192);
        return container;
    }
}
